package com.netty.server;

import java.net.InetSocketAddress;
import java.util.Map;

import com.alibaba.fastjson.JSON;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 服务端处理器 
 * 
 * @author shengli.hu
 */
@Slf4j
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {
	
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = insocket.getAddress().getHostAddress();
        log.info("收到客户端[ip:" + clientIp + "]连接");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 当出现异常就关闭连接
        ctx.close();
    }

/*	@Override
	protected void messageReceived(ChannelHandlerContext ctx, String bodyMsg) throws Exception {
       StringBuilder sb = null;
        Map<String, Object> result = null;
        try {
        	log.info("收到客户端消息:{}", bodyMsg);
            // 报文解析处理
            sb = new StringBuilder();
            result = JSON.parseObject(bodyMsg);
            sb.append(result);
            sb.append("解析成功");
            sb.append("\n");
            ctx.writeAndFlush(sb);
        } catch (Exception e) {
            String errorCode = "-1\n";
            ctx.writeAndFlush(errorCode);
            log.error("报文解析失败: " + e.getMessage());
        }
	}
*/
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String bodyMsg) throws Exception {
	       StringBuilder sb = null;
	        Map<String, Object> result = null;
	        try {
	        	log.info("收到客户端消息:{}", bodyMsg);
	            // 报文解析处理
	            sb = new StringBuilder();
	            result = JSON.parseObject(bodyMsg);
	            sb.append(result);
	            sb.append("解析成功");
	            sb.append("\n");
	            ctx.writeAndFlush(sb);
	        } catch (Exception e) {
	            String errorCode = "-1\n";
	            ctx.writeAndFlush(errorCode);
	            log.error("报文解析失败: " + e.getMessage());
	        }
	}

}
